import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import {
  Modal,
  Row,
  Col,
  Input,
  Form,
  TreeSelect,
  Button,
  message,
} from 'antd';
import styles from './index.less';
const { TreeNode } = TreeSelect;
import { find } from 'lodash';

/**
 * 用户管理界面。这里可以进行用户的新建、编辑、删除。可以给用户分配角色
 * 列表展示数据库中所有用户。账户和密码都会进行展示。
 * @param props
 * @returns
 */
const CreatEditDepartment = (props: any) => {
  const {
    dispatch,
    loading,
    createDepart,
    setCreateDepart,
    depart,
    fetchDepartsData,
    departSource,
    departData,
  } = props;
  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };
  const [form] = Form.useForm();

  const [value, setValue] = useState(undefined);
  const onChange = (tag) => {
    setValue(tag);
  };

  useEffect(() => {
    if (createDepart && depart && depart._id) {
      form.setFieldsValue({
        ...depart,
        departParentId: depart.departParentId
          ? JSON.parse(depart.departParentId).id
          : '',
      });
    } else {
      createDepart && form.resetFields();
    }
  }, [createDepart]);

  const handleCancel = () => {
    setCreateDepart(false);
  };

  const handleSave = async () => {
    const res = await form.validateFields();
    let parent = find(departData, (depart) => {
      return depart._id === value;
    });
    if (parent) {
      res.departParentId = JSON.stringify({
        id: parent._id,
        name: parent.departName,
      });
    }
    if (depart && depart._id) {
      dispatch({
        type: 'enoadRBAC/updateDepart',
        payload: { ...res, _id: depart._id },
      }).then((res) => {
        if (res) {
          message.success(res.msg);
          setCreateDepart(false);
          fetchDepartsData();
        }
      });
    } else {
      dispatch({ type: 'enoadRBAC/createDepart', payload: res }).then((res) => {
        if (res) {
          message.success(res.msg);
          setCreateDepart(false);
          fetchDepartsData();
        }
      });
    }
  };

  return (
    <>
      <Modal
        title={depart && depart._id ? '编辑部门' : '新建部门'}
        destroyOnClose
        visible={createDepart}
        width={800}
        getContainer={false}
        maskClosable={false}
        onCancel={handleCancel}
        onOk={handleSave}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取 消
          </Button>,
          <Button
            key="submit"
            loading={
              loading.effects['enoadRBAC/createDepart'] ||
              loading.effects['enoadRBAC/updateDepart']
            }
            disabled={
              loading.effects['enoadRBAC/createDepart'] ||
              loading.effects['enoadRBAC/updateDepart']
            }
            type="primary"
            onClick={handleSave}
          >
            确 定
          </Button>,
        ]}
      >
        <Row>
          <Col span={24}>
            <Form form={form}>
              <Form.Item
                {...formItemLayout}
                labelAlign={'left'}
                rules={[{ required: true, message: '请输入部门名称' }]}
                label="部门名称"
                name="departName"
              >
                <Input
                  style={{ borderRadius: '16px' }}
                  placeholder={'请输入部门名称'}
                  type="input"
                />
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                labelAlign={'left'}
                rules={[{ required: true, message: '请输入部门编号' }]}
                label="部门编号"
                name="departId"
              >
                <Input
                  style={{ borderRadius: '16px' }}
                  placeholder={'请输入部门编号'}
                  type="input"
                />
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                labelAlign={'left'}
                rules={[{ required: false, message: '请选择上级部门' }]}
                label="上级部门"
                name="departParentId"
              >
                <TreeSelect
                  showSearch
                  value={value}
                  dropdownStyle={{ overflow: 'auto' }}
                  placeholder="请选择上级部门"
                  allowClear
                  treeDefaultExpandAll
                  onChange={onChange}
                  treeData={departSource}
                />
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                labelAlign={'left'}
                rules={[{ required: false, message: '请输入部门权限' }]}
                label="部门权限"
                name="departRoleId"
              >
                <Input
                  style={{ borderRadius: '16px' }}
                  placeholder={'请输入部门权限'}
                  type="input"
                />
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Modal>
    </>
  );
};
//关联到用户权限管理state的models中。
export default connect(({ enoadRBAC, loading }) => ({
  ...enoadRBAC,
  loading,
}))(CreatEditDepartment);
